package ch.mylonas.saometer.data;

import processing.core.PApplet;
import processing.core.PConstants;
import processing.serial.Serial;
import ch.mylonas.saometer.config.SaoMeterConfig;

public class SerialDataV2 extends SerialDataCommon implements Runnable, PConstants, SerialData{

	int LINE_FEED=10;

	SaoMeterConfig saoMeterConfig;

	Thread thread;
	Serial serial;
	Boolean started = true;

	public SerialDataV2(){
		super();
	}

	public void init(){

		this.nrOfDataPoints = saoMeterConfig.getNrDataPoints();
		this.data = new int[NUMBER_OF_CHANNELS][this.nrOfDataPoints];
		this.resetData();

	}


	@Override
	public void run() {
		while(started){

			if(isRunning){

				String s = serial.readStringUntil(LINE_FEED);
				if(s != null){
					String a[] = PApplet.split(s, ',');

					if(a.length == NUMBER_OF_CHANNELS){
						int[] newData = new int[2];
						newData[0] = (int)PApplet.parseInt(a[0]);
						newData[1] = (int)PApplet.parseInt(PApplet.trim(a[1]));

						this.shiftArray(newData);
					}
				}
			}

		}

	}


	@Override
	public int[] getData(int channel) {
		return this.data[channel];
	}

	@Override
	public int getLastValue(int channel) {
		return this.data[channel][this.nrOfDataPoints-1];
	}

	public void setSaoMeterConfig(SaoMeterConfig saoMeterConfig) {
		this.saoMeterConfig = saoMeterConfig;
	}

	@Override
	public void setMyParent(PApplet myParent) {
		this.myParent = myParent;
		this.serial = new Serial(myParent, Serial.list()[0], 115200);

		// start the thread
		this.isRunning = true;
		thread = new Thread(this);
		thread.start();
	}

}
